package com.george.shiro.model.service.impl;

import com.george.shiro.model.entity.RoleResources;
import com.george.shiro.model.dao.RoleResourcesMapper;
import com.george.shiro.model.service.IRoleResourcesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author george
 * @since 2019-05-21
 */
@Service
public class RoleResourcesServiceImpl extends ServiceImpl<RoleResourcesMapper, RoleResources> implements IRoleResourcesService {

    @Override
    public void addRoleResources(Long roleId, String resourcesIds) {
        //删除
        removeByRoleId(roleId);
        //添加
        if (!StringUtils.isEmpty(resourcesIds)) {
            String[] resourcesArr = resourcesIds.split(",");
            if (resourcesArr.length == 0) {
                return;
            }
            RoleResources r = null;
            List<RoleResources> roleResources = new ArrayList<>();
            for (String ri : resourcesArr) {
                if (StringUtils.isEmpty(ri)) {
                    continue;
                }
                r = new RoleResources();
                r.setRoleId(roleId);
                r.setResourcesId(Long.parseLong(ri));
                r.setCreateTime(new Date());
                r.setUpdateTime(new Date());
                roleResources.add(r);

            }
            if (roleResources.size() == 0) {
                return;
            }
            this.saveBatch(roleResources);
        }
    }

    private void removeByRoleId(Long roleId) {
        this.baseMapper.deleteByRoleId(roleId);
    }
}
